﻿Imports System.Timers
Imports System.Collections

''' <summary>
''' This is a game component that implements IUpdateable.
''' </summary>


Public Class SpawnManager
    Inherits Microsoft.Xna.Framework.GameComponent

    Public WithEvents Spawns As New ArrayList
    Public WithEvents SpawnTimerChecker As New System.Timers.Timer With {.Enabled = True, .Interval = 1000} ' Im checking the global list of spawntimers every 5 sec to see who is ready to be spawned.
    Private _WorldManager As WorldManager
    Private _SpriteManager As SpriteManager

    Public Structure Spawn
        Public Sprite As Sprite
        Public Timer As Timer
    End Structure

    Public Sub New(ByVal Game As DanoQuest)
        MyBase.New(Game)
        Me.Game.Components.Add(Me)
        _WorldManager = Game.Components.OfType(Of WorldManager).ToList.Item(0)
        _SpriteManager = Game.Components.OfType(Of SpriteManager).ToList.Item(0)
            For Each Spawn As WorldManager.Spawn In _WorldManager.SpawnData
                Spawns.Add(New Spawn With {.Sprite = New Sprite(Spawn.Name, Spawn.Coords, Spawn.Timer), .Timer = New Timer With {.Interval = 100, .Enabled = True, .AutoReset = False}})
            Next
    End Sub

    ''' <summary>
    ''' Allows the game component to perform any initialization it needs to before starting
    ''' to run.  This is where it can query for any required services and load content.
    ''' </summary>
    Public Overrides Sub Initialize()
        ' TODO: Add your initialization code here
        MyBase.Initialize()
    End Sub

    ''' <summary>
    ''' Allows the game component to update itself.
    ''' </summary>
    ''' <param name="gameTime">Provides a snapshot of timing values.</param>
    Public Overrides Sub Update(ByVal gameTime As GameTime)
        ' TODO: Add your update code here
        MyBase.Update(gameTime)
    End Sub

    Public Sub SpawnTimerCheck() Handles SpawnTimerChecker.Elapsed
        If Spawns.Count > 0 Then
            Dim IndexToRemove As New ArrayList
            For Each Spawn As Spawn In Spawns
                If Spawn.Timer.HasElapsed Then
                    _SpriteManager.Add(Spawn.Sprite) 'Spawn Sprite if timer has elapsed
                    IndexToRemove.Add(Spawns.IndexOf(Spawn))
                End If
            Next
            IndexToRemove.Reverse()
            For Each I As Integer In IndexToRemove
                Spawns.RemoveAt(I)
            Next
        End If
    End Sub

    Public Sub ResetTimer(ByVal Sprite As Sprite)
        For Each Spawn As WorldManager.Spawn In _WorldManager.SpawnData
            If Spawn.Coords = Sprite.Stats.SpawnLoc Then
                Spawns.Add(New Spawn With {.Sprite = New Sprite(Spawn.Name, Spawn.Coords, Spawn.Timer), .Timer = New Timer With {.Interval = Spawn.Timer * 1000, .Enabled = True, .AutoReset = False}})
                Exit For
            End If
        Next
    End Sub

End Class

